document.addEventListener("DOMContentLoaded", function() {
  var ge = function(id) { return document.getElementById(id); }
  var html = [];
  var render = function() {
    var pages = localStorage["pages"].split(',');

    var n = 0;
    for (var p = 0; p < pages.length; p++) {
      var page = pages[p];
      if (!page) continue;
      n++;
      html.push('<div class="row '+page+'"><a onclick="goTo(\''+page+'\');return false;" href=""><div class="img"></div><span id="link_'+page+'"></span></a></div>');
    }

    var keys = [];
    for (var p in pages) {
      keys.push(pages[p]);
    }
    var requests = [{action:'lang_num', keys:keys}/*, {action:'images'}*/];
    
    if (localStorage['sharePopup'] != 0) {
      html.push('<div class="sep"></div><div class="row share"><a onclick="share();return false;" href=""><div class="img"></div><span id="link_share"></span></a></div>');
      requests.push({action:'lang', keys:['share_context_menu_label']});
    }

    ge('links').innerHTML = html.join('');
    
    chrome.extension.sendRequest(requests, function(res) {
      for (var i=0; i< res['lang_num'].length;i++) {
        var r = res['lang_num'][i];
        ge('link_'+r.key).innerHTML = r.text;
      }
      /*
      for (i in res['images'] ) {
        var img = res['images'][i];
        if(ge('img_'+i))ge('img_'+i).src = (img || res['images']['def']);
      }
      */
      for (i in res['lang'] ) {
        var r = res['lang'][i];
        if (r.key == 'share_context_menu_label') {
          ge('link_share').innerHTML = r.text;
        }
      }
    });
  }
  
  if (!localStorage['pages'] || !localStorage['notify']) {
    chrome.extension.sendRequest({action:'default'}, function(res) {
      render();
    });
  } else {
    render();
  }

});

function goTo(page, oid) {
  chrome.extension.sendRequest([{action: 'goto', page: page, oid: oid}]);
}

function share() {
  chrome.extension.sendRequest([{action:'share'}]);
}
